﻿using UnityEngine;
using UnityEngine.Helper;
using UnityEngine.UI;

namespace UnityEditor.UI
{
    [CustomEditor(typeof(DynamicRawImage))]
    public class DynamicRawImageEditor : RawImageEditor
    {
        private Texture lastTexture = null;
        private DynamicAtlasPreviewGUI _previewGUI;
        protected override void OnEnable()
        {
            base.OnEnable();
            _previewGUI = new DynamicAtlasPreviewGUI((target as DynamicRawImage).texture as Texture2D);
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            DynamicRawImage myScript = (DynamicRawImage)target;
            GUILayout.Space(5);
            EditorGUILayout.LabelField("DynamicRawImage");
            GUILayout.Space(5);
            myScript.mGroup = (DynamicAtlasGroup)EditorGUILayout.EnumPopup("Group", myScript.mGroup);
            //EditorGUILayout.LabelField("Texture Path", myScript.currentPath);

            GUILayout.Space(5);


            if (EditorApplication.isPlaying)
            {
                _previewGUI.OnInspectorGUI(myScript.mGroup);
            }
            else
            {
                if ((lastTexture != myScript.texture) || (myScript.texture != null && myScript.spritePath == null))
                {
                    lastTexture = myScript.texture;
                    string path = PathUtil.RemoveResourcePath(AssetDatabase.GetAssetPath(myScript.texture));
                    myScript.spritePath = path;
                }

                if (myScript.texture == null)
                {
                    lastTexture = null;
                    myScript.spritePath = null;
                }
            }
        }

        public override void OnPreviewGUI(Rect rect, GUIStyle background)
        {
            _previewGUI.OnPreviewGUI(base.OnPreviewGUI,rect,background,(target as DynamicRawImage).canvasRenderer.GetColor());
        }
    }
}
